package tool

import java.awt.{SystemTray, TrayIcon}
import java.io.File

import javafx.application.Platform
import javafx.event.EventHandler
import javafx.stage.{Stage, WindowEvent}
import javax.imageio.ImageIO
import login.Login
import mainInterface.MainInterface
import org.apache.commons.io.FileUtils
import utils.Utils

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global


/**
 * Created by yz on 2019/3/25
 */
object Tool {
  val userPath = System.getProperty("user.home")
  val workSpace = new File("workspace")
  val baseDir = new File("./").getAbsolutePath
  val binPath = new File("bin")
  val nativePath = new File(binPath, "native")
  val runPidFile = new File(workSpace, "RUNNING_PID")
  val pidFile = new File(workSpace, "pid.txt")
  val jreBinDir = new File(binPath, "jre1.8.0_112/bin")
  val h2File = new File(workSpace, "../h2/data").getAbsolutePath
  val licenceFile = new File(baseDir, "license.txt")
  val port = 9004
  val softName = "糖尿病数据分析软件"

  def stopServer = {
    if (pidFile.exists()) {
      val pid = FileUtils.readFileToString(pidFile).trim
      val command = s"taskkill /pid ${pid} /T /F"
      Utils.callScript(workSpace, ArrayBuffer(command))
      pidFile.delete()
    }

    if (runPidFile.exists()) {
      val pid = FileUtils.readFileToString(runPidFile).trim
      val command = s"taskkill /f /pid ${pid}"
      Utils.callScript(workSpace, ArrayBuffer(command))
      runPidFile.delete()
    }

  }

  def exit = {
    Tool.stopServer
    SystemTray.getSystemTray.getTrayIcons.find { icon =>
      icon.getToolTip == s"${Tool.softName}"
    }.map { icon =>
      SystemTray.getSystemTray.remove(icon)
    }
    Platform.exit()
  }

  def runServer = {
    stopServer
    val liveBatFile = new File("../bin", "live_dm-1.0/bin/live_dm.bat")
    val command =
      s"""
         |set PATH=${jreBinDir};%PATH%
         |set T=%TEMP%\\sthUnique.tmp
         |wmic process where (Name="WMIC.exe" AND CommandLine LIKE "%%%TIME%%%") get ParentProcessId /value | find "ParentProcessId" >%T%
         |set /P A=<%T%
         |set PID=%A:~16%
         |echo %PID% >pid.txt
         |${liveBatFile} -Dslick.dbs.default.db.url="jdbc:h2:${h2File}" -Dmy.baseDir=${baseDir} -Dhttp.port=${port}
           """.stripMargin
    Future {
      Utils.callScript(workSpace, ArrayBuffer(command))
    }
  }

  def enterMain(stage: Stage) = {
    val all = new MainInterface
    stage.setScene(all.getScene)
    stage.centerOnScreen()
  }

  def enterLogin(stage: Stage) = {
    val login = new Login
    stage.setScene(login.getScene)
    stage.centerOnScreen()
  }


}
